<template>
  <div class="ai-assistant-container">
    <!-- 悬浮按钮 -->
    <div 
      class="ai-toggle-btn" 
      @click="toggleAssistant"
      :class="{ 'active': isAssistantOpen }">
      <i class="el-icon-headset" v-if="!isAssistantOpen"></i>
      <i class="el-icon-close" v-else></i>
    </div>

    <!-- AI助手对话框 -->
    <div v-if="isAssistantOpen" class="ai-assistant-dialog">
      <div class="ai-header">
        <h3><i class="el-icon-robot"></i> 智能商城助手</h3>
        <i class="el-icon-close close-btn" @click="toggleAssistant"></i>
      </div>

      <div class="ai-content">
        <!-- 对话记录区域 -->
        <div class="chat-history" ref="chatHistory">
          <div 
            v-for="(message, index) in chatMessages" 
            :key="index"
            :class="['message', message.type, message.styleClass || '']">
            <div class="avatar">
              <i v-if="message.type === 'user'" class="el-icon-user"></i>
              <i v-else class="el-icon-robot"></i>
            </div>
            <div class="message-content">
              <div class="text" v-html="formatMessage(message.content)"></div>
              <div class="timestamp">{{ message.time }}</div>
            </div>
          </div>
          
          <!-- 加载状态 -->
          <div v-if="isLoading" class="message ai">
            <div class="avatar">
              <i class="el-icon-robot"></i>
            </div>
            <div class="message-content">
              <div class="text typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 功能快捷按钮 -->
        <div v-if="chatMessages.length === 0" class="quick-actions">
          <div class="action-title">您好！我是您的智能购物助手，我可以帮您：</div>
          <div class="action-buttons">
            <el-button 
              v-for="(action, index) in quickActions" 
              :key="index"
              size="small" 
              @click="handleQuickAction(action)"
              class="action-btn">
              {{ action.label }}
            </el-button>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <el-input
            v-model="userInput"
            placeholder="请输入您的问题..."
            @keyup.enter.native="sendMessage"
            :disabled="isLoading">
            <template #suffix>
              <i 
                class="el-icon-s-promotion send-btn" 
                @click="sendMessage"
                :class="{ 'disabled': !userInput.trim() || isLoading }"></i>
            </template>
          </el-input>
        </div>
      </div>
      
      <!-- 底部快捷操作按钮 -->
      <div class="ai-footer">
        <div class="footer-buttons">
          <el-button 
            size="mini" 
            @click="handleFooterAction('view_orders')"
            class="footer-btn">
            查看订单信息
          </el-button>
          <el-button 
            size="mini" 
            @click="handleFooterAction('view_cart')"
            class="footer-btn">
            查看购物车内容
          </el-button>
          <el-button 
            size="mini" 
            @click="handleFooterAction('view_shipping')"
            class="footer-btn">
            查看发货信息
          </el-button>
          <el-button 
            size="mini" 
            @click="handleFooterAction('view_refund')"
            class="footer-btn">
            查看退款信息
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "AiAssistant",
  data() {
    return {
      isAssistantOpen: false,
      userInput: '',
      isLoading: false,
      chatMessages: [
        {
          type: 'ai',
          content: '您好！我是智能商城助手，有什么我可以帮您的吗？',
          time: this.getCurrentTime()
        }
      ],
      quickActions: [
        { label: '推荐热门手办', action: 'recommend_hot' },
        { label: '帮我比价', action: 'compare_price' },
        { label: '查看订单信息', action: 'view_orders' },
        { label: '查看购物车', action: 'view_cart' },
        { label: '查看发货信息', action: 'view_shipping' },
        { label: '查看退款信息', action: 'view_refund' }
      ]
    };
  },
  methods: {
    toggleAssistant() {
      this.isAssistantOpen = !this.isAssistantOpen;
      if (this.isAssistantOpen) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    
    getCurrentTime() {
      const now = new Date();
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const chatHistory = this.$refs.chatHistory;
        if (chatHistory) {
          chatHistory.scrollTop = chatHistory.scrollHeight;
        }
      });
    },
    
    formatMessage(content) {
      // 转义HTML特殊字符以防止XSS攻击，同时保留换行符
      if (!content) return '';
      // 先转义HTML特殊字符
      let escapedContent = content
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
      // 将换行符转换为<br>标签
      return escapedContent.replace(/\n/g, '<br>');
    },
    
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;
      
      // 添加用户消息
      const userMessage = {
        type: 'user',
        content: this.userInput,
        time: this.getCurrentTime()
      };
      this.chatMessages.push(userMessage);
      
      // 清空输入框
      const userQuery = this.userInput;
      this.userInput = '';
      
      // 滚动到底部
      this.scrollToBottom();
      
      // 显示加载状态
      this.isLoading = true;
      
      try {
        // 调用AI助手API
        const response = await request.post('/ai/assistant', {
          query: userQuery
        });
        
        // 添加AI回复
        const aiMessage = {
          type: 'ai',
          content: response.data.answer,
          time: this.getCurrentTime()
        };
        this.chatMessages.push(aiMessage);
      } catch (error) {
        console.error('AI助手调用失败:', error);
        let errorMessageContent = '抱歉，我暂时无法回答您的问题，请稍后再试。';
        
        // 根据错误类型提供更具体的错误信息
        if (error.response) {
          if (error.response.status === 401) {
            errorMessageContent = '请先登录后再使用AI助手功能。';
          } else if (error.response.status === 500) {
            errorMessageContent = '服务器内部错误，请稍后再试或联系管理员。';
          }
        }
        
        const errorMessage = {
          type: 'ai',
          content: errorMessageContent,
          time: this.getCurrentTime()
        };
        this.chatMessages.push(errorMessage);
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    
    async handleQuickAction(action) {
      let query = '';
      switch (action.action) {
        case 'recommend_hot':
          query = '推荐一些热门手办商品';
          break;
        case 'compare_price':
          query = '帮我对比几款手办的价格';
          break;
        case 'view_orders':
          // 直接调用获取订单信息的API
          await this.fetchUserOrders();
          return;
        case 'view_cart':
          // 直接调用获取购物车信息的API
          await this.fetchUserCart();
          return;
        case 'view_shipping':
          // 直接调用获取发货信息的API
          await this.fetchUserShipping();
          return;
        case 'view_refund':
          // 直接调用获取退款信息的API
          await this.fetchUserRefund();
          return;
        default:
          query = action.label;
      }
      
      this.userInput = query;
      this.sendMessage();
    },
    
    // 处理底部快捷按钮点击事件
    async handleFooterAction(actionType) {
      // 添加用户操作消息到对话记录
      let actionText = '';
      switch (actionType) {
        case 'view_orders':
          actionText = '查看订单信息';
          break;
        case 'view_cart':
          actionText = '查看购物车内容';
          break;
        case 'view_shipping':
          actionText = '查看发货信息';
          break;
        case 'view_refund':
          actionText = '查看退款信息';
          break;
      }
      
      // 添加用户操作消息到对话记录
      const userActionMessage = {
        type: 'user',
        styleClass: 'action-message',
        content: actionText,
        time: this.getCurrentTime()
      };
      this.chatMessages.push(userActionMessage);
      
      // 滚动到底部
      this.scrollToBottom();
      
      // 执行相应的操作
      switch (actionType) {
        case 'view_orders':
          await this.fetchUserOrders();
          break;
        case 'view_cart':
          await this.fetchUserCart();
          break;
        case 'view_shipping':
          await this.fetchUserShipping();
          break;
        case 'view_refund':
          await this.fetchUserRefund();
          break;
      }
    },
    
    async fetchUserOrders() {
      this.isLoading = true;
      try {
        const response = await request.get('/ai/user/orders');
        const orders = response.data;
        
        if (orders && orders.length > 0) {
          let content = '您的订单信息如下：\n\n';
          orders.forEach((order, index) => {
            content += `${index + 1}. 订单号：${order.orderNo}\n`;
            content += `   商品名称：${order.orderName}\n`;
            content += `   数量：${order.count}\n`;
            content += `   价格：¥${order.payPrice}\n`;
            content += `   状态：${this.getOrderStatus(order.state)}\n`;
            content += `   下单时间：${this.formatDate(order.createTime)}\n`;
            if (order.paymentTime) {
              content += `   付款时间：${this.formatDate(order.paymentTime)}\n`;
            }
            content += '\n';
          });
          
          const aiMessage = {
            type: 'ai',
            content: content,
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        } else {
          const aiMessage = {
            type: 'ai',
            content: '您还没有订单信息。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        }
      } catch (error) {
        console.error('获取订单信息失败:', error);
        // 检查是否因为未登录导致的错误
        if (error.response && error.response.status === 401) {
          const errorMessage = {
            type: 'ai',
            content: '请先登录后再查询订单信息。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        } else {
          const errorMessage = {
            type: 'ai',
            content: '获取订单信息失败，请稍后再试。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        }
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    
    async fetchUserCart() {
      this.isLoading = true;
      try {
        const response = await request.get('/ai/user/cart');
        const cartItems = response.data;
        
        if (cartItems && cartItems.length > 0) {
          let content = '您的购物车中有以下商品：\n\n';
          cartItems.forEach((item, index) => {
            content += `${index + 1}. 商品名称：${item.orderName}\n`;
            content += `   数量：${item.count}\n`;
            content += `   价格：¥${item.payPrice}\n`;
            content += `   添加时间：${this.formatDate(item.createTime)}\n\n`;
          });
          
          const aiMessage = {
            type: 'ai',
            content: content,
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        } else {
          const aiMessage = {
            type: 'ai',
            content: '您的购物车是空的。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        }
      } catch (error) {
        console.error('获取购物车信息失败:', error);
        // 检查是否因为未登录导致的错误
        if (error.response && error.response.status === 401) {
          const errorMessage = {
            type: 'ai',
            content: '请先登录后再查询购物车信息。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        } else {
          const errorMessage = {
            type: 'ai',
            content: '获取购物车信息失败，请稍后再试。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        }
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    
    async fetchUserShipping() {
      this.isLoading = true;
      try {
        const response = await request.get('/ai/user/shipping');
        const shippingItems = response.data;
        
        if (shippingItems && shippingItems.length > 0) {
          let content = '您的发货信息如下：\n\n';
          shippingItems.forEach((item, index) => {
            content += `${index + 1}. 订单号：${item.orderNo}\n`;
            content += `   商品名称：${item.orderName}\n`;
            content += `   数量：${item.count}\n`;
            content += `   价格：¥${item.payPrice}\n`;
            content += `   发货状态：已发货\n`;
            content += `   下单时间：${this.formatDate(item.createTime)}\n`;
            if (item.paymentTime) {
              content += `   付款时间：${this.formatDate(item.paymentTime)}\n`;
            }
            content += '\n';
          });
          
          const aiMessage = {
            type: 'ai',
            content: content,
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        } else {
          const aiMessage = {
            type: 'ai',
            content: '您目前没有已发货的订单。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        }
      } catch (error) {
        console.error('获取发货信息失败:', error);
        // 检查是否因为未登录导致的错误
        if (error.response && error.response.status === 401) {
          const errorMessage = {
            type: 'ai',
            content: '请先登录后再查询发货信息。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        } else {
          const errorMessage = {
            type: 'ai',
            content: '获取发货信息失败，请稍后再试。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        }
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    
    async fetchUserRefund() {
      this.isLoading = true;
      try {
        const response = await request.get('/ai/user/refund');
        const refundItems = response.data;
        
        if (refundItems && refundItems.length > 0) {
          let content = '您的退款信息如下：\n\n';
          refundItems.forEach((item, index) => {
            content += `${index + 1}. 订单号：${item.orderNo}\n`;
            content += `   商品名称：${item.orderName}\n`;
            content += `   数量：${item.count}\n`;
            content += `   价格：¥${item.payPrice}\n`;
            content += `   退款状态：退款中\n`;
            content += `   下单时间：${this.formatDate(item.createTime)}\n`;
            if (item.paymentTime) {
              content += `   付款时间：${this.formatDate(item.paymentTime)}\n`;
            }
            content += '\n';
          });
          
          const aiMessage = {
            type: 'ai',
            content: content,
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        } else {
          const aiMessage = {
            type: 'ai',
            content: '您目前没有退款中的订单。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(aiMessage);
        }
      } catch (error) {
        console.error('获取退款信息失败:', error);
        // 检查是否因为未登录导致的错误
        if (error.response && error.response.status === 401) {
          const errorMessage = {
            type: 'ai',
            content: '请先登录后再查询退款信息。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        } else {
          const errorMessage = {
            type: 'ai',
            content: '获取退款信息失败，请稍后再试。',
            time: this.getCurrentTime()
          };
          this.chatMessages.push(errorMessage);
        }
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    
    getOrderStatus(state) {
      const statusMap = {
        1: '已支付',
        2: '未支付',
        3: '已取消',
        4: '已发货',
        5: '已完成',
        6: '退款中'
      };
      return statusMap[state] || '未知状态';
    },
    
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    }
  }
};
</script>

<style scoped>
.ai-assistant-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
}

.ai-toggle-btn {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(79, 70, 229, 0.4);
  transition: all 0.3s ease;
  font-size: 24px;
}

.ai-toggle-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 25px rgba(79, 70, 229, 0.6);
}

.ai-toggle-btn.active {
  background: linear-gradient(135deg, #ef4444 0%, #f97316 100%);
}

.ai-assistant-dialog {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.ai-header {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.ai-header h3 i {
  margin-right: 8px;
}

.close-btn {
  cursor: pointer;
  font-size: 20px;
  transition: transform 0.3s ease;
}

.close-btn:hover {
  transform: rotate(90deg);
}

.ai-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-history {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  gap: 12px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 16px;
}

.message.user .avatar {
  background: #dbeafe;
  color: #3b82f6;
}

.message.ai .avatar {
  background: #f0f9ff;
  color: #0ea5e9;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message.user .message-content {
  align-items: flex-end;
}

.text {
  padding: 12px 16px;
  border-radius: 18px;
  background: #f1f5f9;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  unicode-bidi: embed;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.message.user .text {
  background: #dbeafe;
  border-bottom-right-radius: 4px;
}

.message.ai .text {
  background: #f0f9ff;
  border-bottom-left-radius: 4px;
}

/* 用户操作消息样式 */
.message.user.action-message .text {
  background: #ddd6fe;
  border: 1px dashed #8b5cf6;
  font-weight: 500;
}

.timestamp {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 4px;
  align-self: flex-start;
}

.message.user .timestamp {
  align-self: flex-end;
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 10px 15px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #94a3b8;
  border-radius: 50%;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.quick-actions {
  padding: 20px;
  text-align: center;
}

.action-title {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 15px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.action-btn {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  font-size: 12px;
  padding: 8px 12px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
  transform: translateY(-2px);
}

.input-area {
  padding: 15px;
  border-top: 1px solid #e2e8f0;
  background: white;
}

.input-area ::v-deep .el-input__inner {
  border-radius: 20px;
  padding: 10px 40px 10px 15px;
}

.send-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #4f46e5;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-btn:hover:not(.disabled) {
  color: #7c3aed;
  transform: translateY(-50%) scale(1.1);
}

.send-btn.disabled {
  color: #cbd5e1;
  cursor: not-allowed;
}

/* 底部快捷按钮样式 */
.ai-footer {
  border-top: 1px solid #e2e8f0;
  padding: 10px;
  background: #f8fafc;
}

.footer-buttons {
  display: flex;
  justify-content: space-between;
}

.footer-btn {
  flex: 1;
  margin: 0 2px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  font-size: 12px;
  padding: 6px 8px;
  transition: all 0.3s ease;
}

.footer-btn:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-assistant-dialog {
    width: 320px;
    height: 500px;
    bottom: 70px;
  }
  
  .message-content {
    max-width: 80%;
  }
  
  .text {
    font-size: 13px;
  }
  
  .footer-buttons {
    flex-wrap: wrap;
  }
  
  .footer-btn {
    margin-bottom: 4px;
  }
}
</style>